package com.biostime.dingdingbox.modules.db.api;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.impl.transformer.StringToInteger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.dingdingbox.common.api.FastResponse;
import com.biostime.dingdingbox.common.api.ListResponse;
import com.biostime.dingdingbox.common.api.ObjResponse;
import com.biostime.dingdingbox.common.web.BaseController;
import com.biostime.dingdingbox.modules.db.dto.BoxDetailDto;
import com.biostime.dingdingbox.modules.db.dto.BoxDto;
import com.biostime.dingdingbox.modules.db.dto.GameStrategyDto;
import com.biostime.dingdingbox.modules.db.dto.RecommendStrategyDto;
import com.biostime.dingdingbox.modules.db.entity.Box;
import com.biostime.dingdingbox.modules.db.entity.GameStrategy;
import com.biostime.dingdingbox.modules.db.entity.MemberBox;
import com.biostime.dingdingbox.modules.db.service.BoxService;
import com.biostime.dingdingbox.modules.db.service.CommentService;
import com.biostime.dingdingbox.modules.db.service.GameStrategyService;
import com.biostime.dingdingbox.modules.db.service.MemberBoxService;
import com.biostime.dingdingbox.modules.db.service.MemberService;
import com.biostime.dingdingbox.modules.db.service.PraiseRecordService;
import com.biostime.dingdingbox.modules.db.service.ReadHistoryService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 玩具盒模块API
 * 
 * @author chenweicheng
 * @version 2016-06-28
 */
@RestController
@RequestMapping(value = "${adminPath}/db/api/box")
public class BoxApi extends BaseController {

	@Autowired
	private BoxService boxService;

	@Autowired
	private MemberBoxService memberBoxService;

	@Autowired
	private PraiseRecordService praiseRecordService;

	@Autowired
	private GameStrategyService gameStrategyService;

	@Autowired
	private CommentService commentService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private ReadHistoryService readHistoryService;

	/**
	 * 获取玩具盒列表
	 */
	@RequestMapping(value = "boxList")
	public ListResponse<BoxDto> boxList(String userId, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		userId = memberService.apiGetUserId(userId);
		List<BoxDto> boxList = new ArrayList<BoxDto>();
		if (userId != null && !userId.equals("")) {
			List<MemberBox> memberBoxList = memberBoxService.apiGetMBByMemberId(userId, null);
			if (memberBoxList != null && !memberBoxList.isEmpty()) {
				boxList = boxService.apiGetBoxList();
			}
		}
		return FastResponse.create().errMsg("获取玩具盒列表成功").list(boxList);
	}

	/**
	 * 获取我的玩具盒列表
	 */
	@RequestMapping(value = "myBoxList")
	public ListResponse<BoxDto> myBoxList(String userId, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		userId = memberService.apiGetUserId(userId);
		List<BoxDto> boxList = new ArrayList<BoxDto>();
		if (userId != null && !userId.equals("")) {
			if (memberBoxService.apiGetMBByMemberId(userId, null) != null) {
				boxList = boxService.apiGetMyBoxList(userId);
			}
		}
		return FastResponse.create().errMsg("获取玩具盒列表成功").list(boxList);
	}

	
	/**
	 * 获取玩具盒详情页
	 */
	@RequestMapping(value = "boxDetail")
	public ObjResponse<BoxDetailDto> boxDetail(String userId, String boxId, HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		String memberId = userId;
		userId = memberService.apiGetUserId(memberId);

		// 新增访问记录
		readHistoryService.insert(request, "box", boxId, userId);

		String message = "获取玩具盒详情页成功";
		int errCode = 0;
		BoxDetailDto detailDto = new BoxDetailDto();
		if (userId != null && !userId.equals("") && boxId != null && !boxId.equals("")) {

			List<MemberBox> memberBoxList = memberBoxService.apiGetMBByMemberId(userId, boxId);
			if (memberBoxList != null && !memberBoxList.isEmpty()) {

				detailDto = boxService.apiGetBoxById(boxId);
				if (detailDto != null) {

					// 推荐玩法
					GameStrategy strategy = gameStrategyService.apiGetRecomStrategy(boxId);
					if (strategy != null) {
						RecommendStrategyDto recomDto = new RecommendStrategyDto();
						recomDto.setPraiseCount(praiseRecordService.apiRecomPraiseCount());
						if (praiseRecordService.apiStrategyPraiseCount(strategy.getId(), userId) > 0) {
							recomDto.setIsPraised(1);
						}
						recomDto.setCommentCount(commentService.apiGetCommentCount(strategy.getId()));
						recomDto.setId(Integer.parseInt(strategy.getId()));
						recomDto.setImgUrl(strategy.getCover());
						detailDto.setRecommendStrategy(recomDto);

					}

					// 更多玩法，默认100条记录
					List<GameStrategyDto> gameStrategyList = strategyList(memberId, boxId, 1, 100, response).getList();
					detailDto.setGameStrategyList(gameStrategyList);
				}
			} else {
				message = "尚未激活该玩具，请输入激活码!";
				errCode = 1;
			}
		}
		return FastResponse.create().errMsg(message).errCode(errCode).obj(detailDto);
	}

	/**
	 * 更多玩法
	 */
	@RequestMapping(value = "strategyList")
	public ListResponse<GameStrategyDto> strategyList(String userId, String boxId, int pageindex, int pagesize,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		userId = memberService.apiGetUserId(userId);
		List<GameStrategyDto> strategyList = new ArrayList<GameStrategyDto>();
		if (userId != null && !userId.equals("")) {

			List<MemberBox> memberBoxList = memberBoxService.apiGetMBByMemberId(userId, boxId);
			if (memberBoxList != null && !memberBoxList.isEmpty()) {
				PageHelper.startPage(pageindex, pagesize);
				strategyList = gameStrategyService.apiGetMoreStrategy(boxId);

				// 获取玩法攻略点赞数
				if (strategyList != null && !strategyList.isEmpty()) {
					for (GameStrategyDto dto : strategyList) {
						dto.setPraiseCount(
								praiseRecordService.apiStrategyPraiseCount(String.valueOf(dto.getId()), null));
						if (praiseRecordService.apiStrategyPraiseCount(String.valueOf(dto.getId()), userId) > 0) {
							dto.setIsPraised(1);
						}
					}
				}

			}
		}
		PageInfo<GameStrategyDto> page = new PageInfo<GameStrategyDto>(strategyList);

		return FastResponse.create().errMsg("获取更多玩法成功").pageIndex(page.getPageNum()).pageSize(page.getPageSize())
				.total((int) page.getTotal()).hasNext(page.isHasNextPage()).list(strategyList);
	}


	@RequestMapping(value = "test")
	public List<Box> show(Box box, Model model) {
		List<Box> boxList = boxService.show();
		model.addAttribute("boxList", boxList);
		return boxList;
	}
	
	public void test() throws JsonProcessingException{
		Box box = new Box();
		ObjectMapper mapper = new ObjectMapper();
		String str = mapper.writeValueAsString(box);
	}
}
